package com.aidong.util;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;


public class ImageUpload {

	/**
	 * 将图片字节流读出为图片
	 * 
	 * @param inputStream
	 * @return path 图片存储路径
	 */
	public static String readBlobOld(String strInputStream,String prefix) {
		String filePath = "/images/" + prefix + "/"; // 文件保存路径
		String savePath = ""; // 数据库保存路径
		try {
			byte[] bs = Base64Coder.decodeLines(strInputStream);
			InputStream inputStream = new ByteArrayInputStream(bs); // 将字符串转为字节流

			Date date = new Date();
			SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
			String timestamp = format.format(date);
			int ramdom = (int) (Math.random() * 10000); // 产生10000以内的整数
			String fileName = timestamp + ramdom + ".jpg"; // 图片名
			String physPath = ReadPropertiesUtil.getIMGUPLOAD();
			savePath += filePath + fileName; // 数据库保存路径
			filePath = physPath + filePath + fileName; // 图片保存路径
			FileOutputStream fileOutputStream = new FileOutputStream(filePath);

			byte[] buffer = new byte[1024];
			int len = 0;

			while ((len = inputStream.read(buffer)) != -1) {
				fileOutputStream.write(buffer, 0, len);
			}
			inputStream.close();
			fileOutputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return savePath;
	}
	public static String readBlob(String strInputStream,String prefix) {
		String filePath = "/images/" + prefix + "/"; // 文件保存路径
		String savePath = ""; // 数据库保存路径
		try {
			 //密钥配置
	        Auth auth = Auth.create(QiniuUtil.ACCESS_KEY, QiniuUtil.SECRET_KEY);
	        //创建上传对象
	        UploadManager uploadManager = new UploadManager();
	        byte[] bs = Base64Coder.decodeLines(strInputStream);
	        try {
	        	String key = System.currentTimeMillis()+".jpg";    
	            //调用put方法上传
	            Response res = uploadManager.put(bs, filePath+key, auth.uploadToken(QiniuUtil.BUCKET_NAME));
	            //打印返回的信息
	            StringMap msp=res.jsonToMap();
	            System.out.println(msp.get("key"));
	            savePath=msp.get("key")+"";
	            } catch (QiniuException e) {
	                //Response r = e.response;
	                e.printStackTrace();
	            }
		} catch (Exception e) {
			e.printStackTrace();
		}
		return savePath;
	}
	/**
	 * 根据外网路径将图片下载到本地
	 * 
	 * @param url
	 * @return
	 * @throws MalformedURLException
	 */
	public static String outerDownload(String imgUrl, String prefix) throws Exception {
		
		String filePath = "/images/" + prefix + "/"; // 文件保存路径
		String savePath = ""; // 数据库保存路径
		try {
			 //密钥配置
	        Auth auth = Auth.create(QiniuUtil.ACCESS_KEY, QiniuUtil.SECRET_KEY);
	        //创建上传对象
	        UploadManager uploadManager = new UploadManager();
	        byte[] bs = Base64Coder.decodeLines(imgUrl);
	        try {
	        	String key = System.currentTimeMillis()+".jpg";    
	            //调用put方法上传
	            Response res = uploadManager.put(bs, filePath+key, auth.uploadToken(QiniuUtil.BUCKET_NAME));
	            //打印返回的信息
	            StringMap msp=res.jsonToMap();
	            System.out.println(msp.get("key"));
	            savePath=msp.get("key")+"";
	            } catch (QiniuException e) {
	                //Response r = e.response;
	                e.printStackTrace();
	            }
		} catch (Exception e) {
			e.printStackTrace();
		}
		return savePath;
	}

	/**
	 * 根据外网路径将图片下载到本地
	 * 
	 * @param url
	 * @return
	 * @throws MalformedURLException
	 */
	public static String outerDownloadOld(String imgUrl, String prefix) throws Exception {
		// 构造URL
		URL url = new URL(imgUrl);
		// 打开连接
		URLConnection con = url.openConnection();
		// 输入流
		InputStream is = con.getInputStream();

		// 数据缓冲
		byte[] bs = new byte[1024];
		// 读取到的数据长度
		int len;
		// 输出的文件流
		File sf = new File("");
		if (!sf.exists()) {
			sf.mkdirs();
		}
		
		String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		int ramdom = (int) (Math.random() * 10000); // 产生10000以内的整数
		String fileName = timestamp + ramdom + ".jpg"; // 图片名
		
		String savePth = "/images/" + prefix + "/" + fileName;
		String physPath = ReadPropertiesUtil.getIMGUPLOAD();
		String filePath = physPath + savePth;
		
		OutputStream os = new FileOutputStream(filePath);
		// 开始读取
		while ((len = is.read(bs)) != -1) {
			os.write(bs, 0, len);
		}
		// 完毕，关闭所有链接
		os.close();
		is.close();
		
		return savePth;
	}

}
